package com.breaktian.assemble.socket.udp;

import com.breaktian.assemble.socket.callback.DataReceive;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


public class UdpServerSocket {
	
	private DatagramSocket udpServerSocket;
	
	private int cache_size = 1024*1024*3;
	

	public UdpServerSocket(int port){
		try {
			udpServerSocket = new DatagramSocket(port, InetAddress.getLocalHost());
//			udpServerSocket.setSoTimeout(200000);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 监听消息
	 * */
	public void listen(DataReceive call){
		if(udpServerSocket==null) throw new IllegalStateException("udpServerSocket为null");
		try {
			byte[] buf = new byte[cache_size]; 
			DatagramPacket packet = new DatagramPacket(buf, buf.length);
			udpServerSocket.receive(packet);
			
			int length = packet.getLength();
			byte[] receiveData = new byte[length];
			System.arraycopy(packet.getData(), 0, receiveData, 0, length); 
			call.onReceive(receiveData);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
	
	
	
	/**
	 * 关闭socket
	 * */
	public void shutDown(){
		if(udpServerSocket==null) throw new IllegalStateException("udpServerSocket为null");
		udpServerSocket.close();
	}
	
	
}
